import React, { PureComponent } from 'react';
import { Icon, Upload, Col, Select, Button, Form, notification } from 'antd';
import { connect } from 'dva';
import "./form.less"
import "../../Common.less"
class PinnerCal extends PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            roadlist: [],
            tdata: [{}]
        }
        this.selectRoad = this.selectRoad.bind(this)
        this.calculate = this.calculate.bind(this)
        this.addRow = this.addRow.bind(this)
        this.removeRow = this.removeRow.bind(this)
        this.validate=this.validate.bind(this)
    }
    async selectRoad(e) {
        console.log(e)
    }
    calculate() {
        const {form,cushionPoint,modalContext}=this.props;
        if (!form.getFieldValue("road")) {
            notification.warn({ message: "请选择路线!" })
            return;
        }
        let list = document.querySelectorAll(".tableBoxS tr .input")
        const len = list.length;
        let arr = []
        let obj = {}
        for (let i = 0; i < len; i++) {
            if (i % 7 == 0) {
                obj = {}
            }
            let node = list[i];
            node.classList.remove("required")
            if (!node.disabled) {
                if (!node.value) {
                    node.classList.add("required")
                    node.focus()
                    notification.warn({ message: "请将字段填写完整!" })
                    return;
                }
                if(node.dataset.validate){
                    if(!this[node.dataset.validate](node.value)){
                        node.classList.add("required")
                        node.focus()
                        notification.warn({ message: `${node.dataset.name}字段格式不正确!` })
                        return;
                    }
                }
                obj[node.dataset.key] = node.value.replace(/\uff0c/g,",")

                if (i % 7 == 6) {
                    arr.push(obj)
                }
            }
        }

       cushionPoint({ cushionPoints: arr, roadlineId: form.getFieldValue("road") }, res => {
            let data = res.data.data;
            if (data && data.length) {
                this.setState({
                    tdata: data
                })
                modalContext.updateModal({
                    visible: true,
                    title: "垫石高程计算(单位:m)",
                    footer:null,
                    event: { code: "pinnerModal" },
                    extra: {
                        tdata:data
                    }
                })
            }
        }, err => {

        })

    }
    validate(str){
        let reg=true;
        str=str.replace(/\uff0c/g,",")
        str=str.replace(/\s/g,"")
        if(str.includes(",")){
            let arr=str.split(",");
            const len=arr.length;
            for (let i = 0; i < len; i++) {
                let item = arr[i];
                try {
                    eval(item)
                } catch (error) {
                    reg=false
                }
            }
        }else{
            reg=typeof(str-0)=="number"?true:false
        }
        return reg;
    }
    async componentDidMount() {
        const { project,loadProjectRoads } = this.props;
        let data = await loadProjectRoads({ projectId: project.id })
        if (data) {
            this.setState({
                roadlist: data.res
            })
        }

    }
    addRow(e, index) {
        e.preventDefault();
        let { tdata } = this.state

        tdata.splice(index + 1, 0, { id: new Date().getTime() })
        this.setState({
            tdata: [...tdata]
        })
    }
    removeRow(e, index) {
        e.preventDefault();

        let { tdata } = this.state
        if (tdata.length < 2) {
            notification.warn({ message: "至少保留一组数据!" })
            return;
        }
        tdata.splice(index, 1)
        this.setState({
            tdata: [...tdata]
        })
    }
    render() {
        const { getFieldDecorator } = this.props.form;
        const { roadlist, tdata } = this.state
        return (
            <div className="PinnerCal">
                <div>
                    <Col span="22">
                        <Form style={{ padding: "15px 15px" }}
                            layout="inline"
                            labelCol={{ span: 5 }}
                            wrapperCol={{ span: 19 }}

                        >
                            <Form.Item style={{ width: "220px" }} label='路线'>
                                {getFieldDecorator('road', {
                                    rules: [
                                        { required: true, message: '请选择路线' }
                                    ],
                                })(
                                    <Select onSelect={this.selectRoad} placeholder="请选择线路">
                                        {
                                            roadlist.map(item => {
                                                return (
                                                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                                )
                                            })
                                        }

                                    </Select>
                                )}
                            </Form.Item>

                            <Form.Item style={{ marginRight: "10px" }}>
                                <Button onClick={this.calculate} type="primary">计算</Button>
                            </Form.Item>
                            <Form.Item style={{ marginRight: "10px" }}>
                                <Upload showUploadList={false} className="modelUpload">
                                    <Button type="primary" > <Icon type="upload" /> 模板上传</Button>
                                </Upload>
                            </Form.Item>
                            <Form.Item>  <Button type="primary"><Icon type="cloud-download" />模板下载</Button></Form.Item>
                        </Form>
                    </Col>
                </div>
                <div className="tableBoxS tcBox">
                    <table style={{ width: "calc(100% - 30px)", margin: "auto" }}>
                        <tbody>
                            <tr className="th">
                                <td>位置</td>
                                <td>桩号(m)</td>
                                <td>角度(度)</td>
                                <td>支座偏移距离(cm)</td>
                                <td>主梁间距(cm)</td>
                                <td>结构高度(cm)</td>
                                <td>支座高度(cm)</td>
                                <td>操作</td>
                            </tr>
                            {
                                tdata && tdata.length ? tdata.map((item, index) => {
                                    return <tr key={'tr'+index}>
                                        <td><input placeholder="请填写墩台号" defaultValue="" data-key="position" className="input" type="text" /></td>
                                        <td><input defaultValue="582.180" data-key="station" className="input" type="number" /></td>
                                        <td><input defaultValue="90" data-key="angle" className="input" type="number" /></td>
                                        <td><input defaultValue="-50" data-key="distance" className="input" type="number" /></td>
                                        <td><input data-name="主梁间距" data-validate="validate" defaultValue="-50,-40,-50,50,40,50" data-key="beamSpacing" className="input" type="text" /></td>
                                        <td><input defaultValue="300" data-key="constructionH" className="input" type="number" /></td>
                                        <td><input defaultValue="300" data-key="supportH" className="input" type="number" /></td>
                                        <td><Icon onClick={e => this.addRow(e, index)} type="plus-square" /><Icon onClick={e => this.removeRow(e, index)} type="minus-square" /></td>
                                    </tr>
                                }) : undefined
                            }
                        </tbody>
                    </table>
                </div>
            </div>
        );
    }
}

export default connect(
    ({
        project: { current }
    }) => {
        return { project: current };
    },
    dispatch => ({
        loadProjectRoads: (values) => dispatch({
            type: 'refRoads/loadProjectRoads',
            payload: values
        }),
        cushionPoint: (values, onSuccess, onError) => dispatch({
            type: 'calculate/cushionPoint',
            payload: {
                values,
                onSuccess,
                onError

            }
        })


    })
)(Form.create('PinnerCal', {

})(PinnerCal));